package com.sx.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sx.ems.utils.PageUtils;
import com.sx.ems.entity.SysRole;
import com.sx.ems.mapper.SysRoleMapper;
import com.sx.ems.service.SysRoleMenuService;
import com.sx.ems.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import static org.apache.commons.lang.StringUtils.isNotBlank;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public PageUtils queryRolePage(Map<String, Object> params) {
        String roleName = (String) params.get("roleName");

        int pageNo = Integer.parseInt(params.get("page").toString());
        int pageSize = Integer.parseInt(params.get("limit").toString());


        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(isNotBlank(roleName), "role_Name", roleName);

        IPage<SysRole> page = this.page(new Page<>(pageNo, pageSize), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public void saveRole(SysRole role) {
        role.setCreateTime(new Date());
        this.save(role);

        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

    }
    @Override
    public void updateRole(SysRole role) {
        this.updateById(role);

        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }
}
